from sqlalchemy.orm import sessionmaker

from api.models.api_models import SpeechSynthesis


class SpeechSynthesisDAO:
    def __init__(self, engine):
        self.engine = engine
        self.Session = sessionmaker(bind=self.engine, expire_on_commit=False)

    def create(self, ppt_file_id, speech_file_id, video_id, speech_synthesis_time, speaker_name=None):
        session = self.Session()
        speech_synthesis = SpeechSynthesis(ppt_file_id=ppt_file_id, speech_file_id=speech_file_id, video_id=video_id, speech_synthesis_time=speech_synthesis_time, speaker_name=speaker_name)
        session.add(speech_synthesis)
        session.commit()
        session.close()
        return speech_synthesis

    def read(self, ppt_file_id, speech_file_id, video_id):
        session = self.Session()
        speech_synthesis = session.query(SpeechSynthesis).filter_by(ppt_file_id=ppt_file_id, speech_file_id=speech_file_id, video_id=video_id).first()
        session.close()
        return speech_synthesis

    def readbyPPT(self, ppt_file_id):
        session = self.Session()
        speech_synthesis = session.query(SpeechSynthesis).filter_by(ppt_file_id=ppt_file_id).first()
        session.close()
        return speech_synthesis

    def update(self, ppt_file_id, speech_file_id, video_id, speech_synthesis_time=None, speaker_name=None):
        session = self.Session()
        speech_synthesis = session.query(SpeechSynthesis).filter_by(ppt_file_id=ppt_file_id, speech_file_id=speech_file_id, video_id=video_id).first()
        if speech_synthesis_time is not None:
            speech_synthesis.speech_synthesis_time = speech_synthesis_time
        if speaker_name is not None:
            speech_synthesis.speaker_name = speaker_name
        session.commit()
        session.close()

    def delete(self, ppt_file_id, speech_file_id, video_id):
        session = self.Session()
        speech_synthesis = session.query(SpeechSynthesis).filter_by(ppt_file_id=ppt_file_id, speech_file_id=speech_file_id, video_id=video_id).first()
        session.delete(speech_synthesis)
        session.commit()
        session.close()